<?php

declare (strict_types=1);

namespace think\admin\support\command;

use think\admin\Command;
use think\admin\extend\DataExtend;
use think\admin\model\SysDict as DictSys;

/**
 * 重置并清理字典(php think xadmin:sysdict)
 * Class Sysdict
 * @package think\admin\support\command
 */
class Sysdict extends Command
{
    /**
     * 指令任务配置
     */
    public function configure()
    {
        $this->setName('xadmin:sysdict');
        $this->setDescription('Clean and Reset SysDict Data for DualengineAdmin');
    }

    /**
     * 任务执行入口
     * @return void
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle()
    {
        $query = DictSys::mQuery()->where(['is_deleted' => 0]);
        $menus = $query->db()->order('sort asc,id asc')->select()->toArray();
        [$total, $count] = [count($menus), 0, $query->empty()];
        $this->setQueueMessage($total, 0, '开始重置系统字典编号...');
        foreach (DataExtend::arr2tree($menus, 'id', 'parentId') as $sub1) {
            $pid1 = $this->write($sub1, 0);
            $this->setQueueMessage($total, ++$count, "重写1级字典：{$sub1['dictLabel']}");
            if (!empty($sub1['sub'])) foreach ($sub1['sub'] as $sub2) {
                $pid2 = $this->write($sub2, $pid1);
                $this->setQueueMessage($total, ++$count, "重写2级字典：-> {$sub2['dictLabel']}");
                if (!empty($sub2['sub'])) foreach ($sub2['sub'] as $sub3) {
                    $this->write($sub3, $pid2);
                    $this->setQueueMessage($total, ++$count, "重写3级字典：-> -> {$sub3['dictLabel']}");
                }
            }
        }
        $this->setQueueMessage($total, $count, "完成重置系统字典编号！");
    }

    /**
     * 写入单项字典数据
     * @param array $arr 单项字典数据
     * @param mixed $pid 上级字典编号
     * @return int|string
     */
    private function write(array $arr, $pid = 0)
    {
        return DictSys::mk()->insertGetId([
            'parent_id' => $pid,
            'dict_label' => $arr['dictLabel'],
            'dict_value' => $arr['dictValue'],
            'category' => $arr['category'],
            'ext_json' => $arr['extJson'],
            'sort' => $arr['sort'],
            'status' => $arr['status'],
            'is_deleted' => $arr['isDeleted'],
            'created_by' => $arr['createdBy'],
            'updated_by' => $arr['updatedBy'],
            'create_time' => $arr['createTime'],
            'update_time' => $arr['updateTime']
        ]);
    }
}